﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VEXREDUS_crc_checksum_calc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bt_calc_checksum_Click(object sender, EventArgs e)
        {
            tb_output.Text = tb_input.Text + "*" + calculate_checksum(tb_input.Text);
        }

        public static string calculate_checksum(string msg)
        {
            Console.WriteLine("calculate checksum - in msg: " + msg + "#####");
            byte crc = 0;

            for (int i = 0; i < msg.Length; i++)
            {
                crc = _crc_ibutton_update(crc, (byte)msg[i]);
            }
            Console.WriteLine("calculate checksum - return: " + crc.ToString("X2"));
            return crc.ToString("X2");

        }

        static byte _crc_ibutton_update(int crc, byte data)
        {
            //byte i;
            crc = crc ^ data;
            for (int i = 0; i < 8; i++)
            {
                if ((crc & 0x01) == 0x01)
                {
                    crc = (crc >> 1) ^ 0x8C;
                }
                else
                {
                    crc >>= 1;
                }
            }

            return Convert.ToByte(crc);
        }

    }
}
